/**
 * @file auditManage.js
 * @Date 2023-09-23, 周六, 15:30
 * @description 文件说明
 *  我的空间审核管理的js文件
 */

$(function (){
	/******************初始化******************/
	const table=layui.table
	const form=layui.form
	const userId=Number(sessionStorage.getItem('userId'))
	// 审核列表请求参数
	let auditParame={
		currPage:1,
		pageSize:10,
		type:null,
		status:null,
		title:null,
		auditUserId:sessionStorage.getItem('UserId'),
	}
	// 复选框选中的idList
	let idList=[]
	// 审核表格
	let auditManageTable=table.render({
		elem: '#auditManageTable'
		,height: '.table'
		,data:[]
		,cols: [[ //表头
			{type: 'checkbox', width:50}
			,{type: 'numbers', title: '序号',}
			,{field: 'title', title: '名称', sort: true}
			,{field: 'type', title: '审核类型', sort: true,templet:function (d){
					switch (d.type) {
						case 0:
							return `<span>数据通道</span>`
						case 1:
							return `<span>申购</span>`
						case 2:
							return `<span>试用申请</span>`
						case 3:
							return `<span>订单</span>`
						case 4:
							return `<span>发布定制</span>`
						case 5:
							return `<span>承接定制</span>`
						case 6:
							return `<span>应用</span>`
						case 8:
							return `<span>治理后数据资源</span>`
					}
				}}
			,{field: 'status', title: '状态',templet:function (d){
				switch (d.status) {
					case 1:
						return `<span>进行中</span>`
					case 2:
						return `<span>成功</span>`
					case 3:
						return `<span>失败</span>`
				}
				}}
			,{field: 'createBy', title: '发起人', sort: true}
			,{field: 'createTime', title: '发起时间',  sort: true}
			,{field: 'auditUserName', title: '审核人', }
			,{field: 'result', title: '流程跟踪',}
			,{ title: '操作', width: 150, templet:function (d) {
					if(d.createUserId === userId && d.auditUserId === userId){
						if(d.status === 1){
							return `<a  class="layui-btn layui-btn-xs text-white mr-2 dataInfo" lay-event="detail">详情</a>
											<a  class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2 auditPass" lay-event="audit">审核</a>`;
						}else{
							return `<a  class="layui-btn layui-btn-xs text-white mr-2 dataInfo" lay-event="detail">详情</a>`;
						}

					}else if(d.createUserId === userId){
						return `<a  class="layui-btn layui-btn-xs text-white mr-2 dataInfo" lay-event="detail">详情</a>`;
					}else if(d.auditUserId === userId){
						if(d.status === 1){
							return `<a  class="layui-btn layui-btn-xs text-white mr-2 dataInfo" lay-event="detail">详情</a>
											<a  class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2 auditPass" lay-event="audit">审核</a>`;
						}else{
							return `<a  class="layui-btn layui-btn-xs text-white mr-2 dataInfo" lay-event="detail">详情</a>`;
						}
					}
				}}
		]]
	});

	/******************事件处理部分******************/
	// 表格操作 详情和审核
	table.on('tool(auditManageTable)',function (obj){
		const data=obj.data;
		const id=data.id;
		if (obj.event==='detail'){//详情
			switch (data.type) {
				case 0://数据通道
					window.location.href = "./.html?sourceId="+id;
					break;
				case 1://数据产品/订单(前往产品)
				case 3:
					window.location.href = "./productDetail.html?productId="+id;
					break;
				case 2://试用申请
					// window.applyTryId =id;
					layer.open({
						type: 2,
						title: "试用申请详情",
						area: ['800px', '480px'],
						content: `./popupPage/applyTryPop.html?associateId=${data.associateId}&&type=1`//使用type来区分是详情还是审核
					});
					break;
				case 5://承接定制
					window.location.href = "./Undertakecustomization.html?customId=" + data.associateId;
					// $.ajax({
       				// 	timeout:30000,
					// 	url: window.Http + "/CustomizeRequest/" + data.associateId,
					// 	type: 'GET',
					// 	headers: {
					// 		'Authorization': "Bearer " + sessionStorage.getItem('Token')
					// 	},
					// 	success: function (res) {
					// 		if (res.code === 200 && res.data.customizeId) {
					// 		} else {
					// 			layer.msg("历史数据，存在异常");
					// 		}
					// 	}
					// })
					break;
				default:
					layer.msg('错误信息')
					break;
			}
		}
		else if (obj.event==='audit'){//审核
			switch (data.type) {
				case 5://定制审核
					layer.open({
						type: 2,
						title: "承接审核",
						area: ['800px', '500px'],
						content: `./popupPage/customizedAuditPop.html?associateId=${data.associateId}&&id=${id}&&createUserId=${data.createUserId}`,
						end:function (index, layero) {
							// console.log('close', index)
							tableRender(auditParame)
						}
					});
					break;
				case 2://试用申请审核
					// window.applyTryId =id;
					layer.open({
						type: 2,
						title: "试用申请审核",
						area: ['800px', '480px'],
						content: `./popupPage/applyTryPop.html?associateId=${data.associateId}&&type=2&&id=${id}`,
						end:function (index, layero) {
							// console.log('close', index)
							tableRender(auditParame)
						}
					});
					break;
				case 3://订单审核
					layer.open({
						type: 2,
						title: "申购审核",
						area: ['1000px', '650px'],
						content: `./popupPage/auditPurchasePop.html?associateId=${data.associateId}&&id=${id}`,
						end:function (index, layero) {
							// console.log('close', index)
							tableRender(auditParame)
						}
					});
					break;
				default:
					layer.msg('错误信息')
					break;

			}
		}
	})
	// 复选框事件
	table.on('checkbox(auditManageTable)', function(obj){
		if (obj.type==='one'){
			idList.push(obj.data.id)
		}else if (obj.type==='all'){
			// 获取表格当前的数据
			const currentData = table.cache['auditManageTable'];
			idList=currentData.map(item=>item.id)

		}
	});
	// 类型和状态下拉框监听
	// 监听类型Select组件的选中事件
	form.on('select(status)', function (data) {
		console.log('选中了：', data.elem[data.elem.selectedIndex].text); // 获取选中文本
		console.log('选中的值：', data.value); // 获取选中值
		if (data.value!==''){
			auditParame.status=Number(data.value)
			tableRender(auditParame)
		}else {
			auditParame.status=null
			tableRender(auditParame)
		}
	})
	// 监听状态Select组件的选中事件
	form.on('select(type)', function (data) {
		console.log('选中了：', data.elem[data.elem.selectedIndex].text); // 获取选中文本
		console.log('选中的值：', data.value); // 获取选中值
		if (data.value!==''){
			auditParame.type=Number(data.value)
			tableRender(auditParame)
		}else {
			auditParame.type=null
			tableRender(auditParame)
		}
	});
	// 搜索按钮
	$('.keyword').on('click','#searchBtn',function (){
		auditParame.title=$('.keyword .layui-input[name="keyword"]').val()
		console.log('auditParame.title', auditParame.title)
		tableRender(auditParame)
	})
	//全部通过审核
	$("#auditHeaderTool").on("click",'#auditAllPass',function (){
		let parame = {
			status:2,
			idList:[],
		}
		parame.idList = idList;
		$.ajax({
       timeout:30000,
			url: window.Http + "/audit/log/operateBatch",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(parame),
			contentType: 'application/json;charset=utf-8',
			success: function (res) {
				if(res.code === 200){
					layer.msg("审核成功", {icon: 1});
					idList=[]
					tableRender(auditParame)
				}else{
					layer.msg(res.msg);
				}
			}
		})

	})

	//全部不通过审核
	$("#auditHeaderTool").on("click",'#auditAllFail',function (){
		let parame = {
			status:3,
			idList:[],
			auditResult:""
		}
		parame.idList = idList;
		layer.open({
			type: 1,
			title: "审核驳回原因",
			area: ['500px', '350px'],
			content: `<div style="padding:20px">
						<div class="layui-form-item layui-form-text" id="1">
						    <label class="layui-form-label" style="width:90px">拒绝理由</label>
						    <div class="layui-input-block" style="padding-top:9px">
						      <textarea placeholder="请输入内容" class="layui-textarea" name="auditResult"></textarea>
						    </div>
						</div>
					</div>`,
			btn: ['提交'],
			yes: function (index, layero) {
				parame.auditResult = $('[name="auditResult"]').val();
				$.ajax({
       				timeout:30000,
					type: 'POST',
					url: window.Http + "/audit/log/operateBatch",
					headers: {
						'Authorization': "Bearer " + sessionStorage.getItem('Token')
					},
					contentType: 'Application/json',
					data:JSON.stringify(parame),
					success: function (res) {
						if(res.code === 200){
							idList=[]
							layer.msg("审核成功", {icon: 1});
							tableRender(auditParame)
							layer.close(index); // 关闭弹窗
						}else{
							layer.msg("审核异常："+`${res.msg}`, {icon: 2});
						}
					}
				})
			}
		});

	})

	/******************功能函数部分******************/
	// 请求审核列表
	function auditListReq(auditParame) {
		return new Promise((function (resolve, reject) {
			$.ajax({
       			timeout:30000,
				type: 'GET',
				url: window.Http + "/audit/log/list",
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data:auditParame,
				success: function (res) {
					if (res.code===200){
						resolve(res)
					}else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))
	}
	// 表格和分页渲染
	function tableRender(auditParame){
		auditListReq(auditParame).then(res=>{
			auditManageTable.reload({data:res.rows})
			layui.laypage.render({
				elem: 'auditManageTablePage', //注意，这里的 test1 是 ID，不用加 # 号
				count: res.total, //数据总数，从服务端得到
				limit: 10,
				groups: 5,
				jump: function (obj, first) {
					if(!first){
						auditParame.currPage=obj.curr
						auditListReq(auditParame).then(res=>{
							auditManageTable.reload({data:res.rows})
						});
					}
				}
			});
		})
	}
	// 初始化渲染表格和分页
	tableRender(auditParame)
	// 待审核总数部分
	function auditNumReq(){
		$.ajax({
       		timeout:30000,
			url: window.Http + "/count/personal/data/table",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: { type: 2,ownUserId:sessionStorage.getItem('UserId') },
			success: function (res) {
				if(res.code === 200){
					$('#toBeAudit').html(res.data.wait||0);
				}else {
					layer.msg(res?.msg)
				}
			}
		})
	}
	auditNumReq()
})